package top.ffhome.springboot.learning.web;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.util.Date;

@Controller
public class IndexController {
    @GetMapping("/")
    public String index() {
        return "index"; // 返回的字符串对应templates目录下的文件名（不包含.html）
    }

    @RequestMapping("/sse")
    @ResponseBody
    public void sse(HttpServletResponse resp) {
        resp.setContentType("text/event-stream");
        resp.setCharacterEncoding("utf-8");
        while (true) {
            try {
                PrintWriter pw = resp.getWriter();
                pw.write("data: " + new Date() + "\n\n");
                pw.flush();
                Thread.sleep(1000);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    @RequestMapping("/sse-retry")
    @ResponseBody
    public void sseRetry(HttpServletResponse resp) {
        resp.setContentType("text/event-stream");
        resp.setCharacterEncoding("utf-8");
        String s = "retry: 5000\n";
        s += "data: " + new Date() + "\n\n";
        try {
            PrintWriter pw = resp.getWriter();
            pw.write(s);
            pw.flush();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
